<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\MoneyLog;
use app\common\model\option\Log as OptionLog;
use app\common\model\option\Option;
use app\common\model\order\Order;
use app\common\model\red\Log;
use app\common\model\red\Log as RedLog;
use app\common\model\User;
use think\Db;
use think\Log as ThinkLog;

/**
 * 定时任务接口（弃用）
 */
class Crontab extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * YS释放
     *
     */
    // public function option_release()
    // {
    //     $check = Option::whereTime('createtime', 'today')->find();
    //     if ($check) {
    //         return '';
    //     }
    //     Db::startTrans();
    //     try {
    //         $data = Option::order('id desc')->find();
    //         if (!$data) {
    //             $param = [
    //                 'options' => 100,
    //                 'day' => 1,
    //                 'total' => 100,
    //             ];
    //         } else {
    //             $option = $data->options + 7;
    //             $param = [
    //                 'options' => $option,
    //                 'day' =>  $data->day + 1,
    //                 'total' => $data->total + $option,
    //             ];
    //         }
    //         $res = Option::create($param);
    //         if ($res) {
    //             $where['invalidtime'] = ['>', time()];
    //             $where['status'] = ['=', 'normal'];
    //             $where['state'] = ['=', '1'];
    //             $logs = Log::all($where);
    //             //总分红包效率
    //             $total = Log::where($where)->sum('efficiency');
    //             foreach ($logs as $v) {
    //                 //个人分红包比例
    //                 $todaypro = $v->efficiency / $total;
    //                 //YS分配数量
    //                 $option = bcmul($res->options, $todaypro, 4);
    //                 //每日YS分配
    //                 OptionLog::income($v->user_id, $option, 2, 100, $v->sn, $res->id);
    //             }
    //         }
    //         Db::commit();
    //     } catch (\Exception $e) {
    //         Db::rollback();
    //         ThinkLog::error($e->getMessage());

    //     }
    // }
    /**
     * 过期红包
     *
     */
    // public function red_envelope()
    // {
    //     RedLog::red_envelope();
    // }
    //会员权益值分红
    public static function vip_commission()
    {
        Db::startTrans();
        try {
            //昨日销量
            $totalMoney = Order::whereIn('status', ['3', '4'])->whereTime('taketime', 'yesterday')->sum('pay_money');
            // $totalMoney = 10000;
            $users = User::where('use_dividend', '>', 0)->where('group_id', '>', 1)->select();
            $total = MoneyLog::whereTime('createtime', 'today')->where('source_type', 700)->sum('money');
            if ($total <= 0) {
                //总权益值
                $total_equity_value = User::where('total_interests', '>', 0)->where('group_id', '>', 1)->sum('total_interests');
                if ($totalMoney > 0 && $total_equity_value > 0) {
                    foreach ($users as $v) {
                        if ($v->total_interests > 0 && $v->use_dividend > 0) {
                            $price = bcmul(bcdiv(bcmul($totalMoney, bcdiv(config('site.dividend_ratio'), 100, 2), 2), $total_equity_value, 2), $v->total_interests, 2);
                            if ($price > 0) {
                                if ($price > $v->use_dividend) {
                                    $price = $v->use_dividend;
                                }
                                MoneyLog::income($v->id, $price, 2, 700, '', $v->total_interests);
                                $v->setDec('use_dividend', $price);
                            }
                        }
                    }
                }
            }
            //昨日支付订单权益值新增
            $orderList = Order::whereIn('status', ['1', '2', '3', '4'])->whereTime('paytime', 'yesterday')->where('settlement', 0)->select();
            foreach ($orderList as $vv) {
                $user = User::get($vv->user_id);
                if ($vv->p_id) {
                    $puser = User::get($vv->p_id);
                    $puser->setInc('total_interests', $vv->p_interests);
                }
                if ($vv->dividend > 0) {
                    $user->setInc('use_dividend', $vv->dividend);
                    if ($user->use_dividend > 0 && $user->frozen_money > 0) {

                        if ($user->use_dividend >= $user->frozen_money) {
                            MoneyLog::income($user->id, $user->frozen_money, 1, 508, $vv->sn);
                            MoneyLog::income($user->id, $user->frozen_money, 2, 509, $vv->sn);
                            $user->setDec('use_dividend', $user->frozen_money);
                        } else {
                            MoneyLog::income($user->id, $user->use_dividend, 1, 508, $vv->sn);
                            MoneyLog::income($user->id, $user->use_dividend, 2, 509, $vv->sn);
                            $user->setDec('use_dividend', $user->use_dividend);
                        }
                    }
                    $user->setInc('total_dividend', $vv->dividend);
                }


                if ($vv->interests > 0) {
                    $user->setInc('total_interests', $vv->interests);
                }
                if ($vv->group_id > 0) {
                    $user->old_grade = $user->group_id;
                    $user->group_id = $vv->group_id;
                }

                $user->save();

                $vv->settlement = 1;
                $vv->save();
            }

            //分红比例自动恢复
            $config = Config::get(['name' => 'dividend_ratio']);
            $config->value = 20;
            $config->save();
            Config::refreshFile();
            Db::commit();
            echo 'success';
        } catch (\Exception $e) {
            Db::rollback();
            ThinkLog::error($e->getMessage());
            echo 'error';
        }
    }
}
